<template>
  <div class="app-container">
    <!-- 数据表格 -->
    <el-table :data="auditList" border style="width: 100%">
      <!-- <el-table-column prop="id" label="ID" width="80"></el-table-column> -->
      <el-table-column prop="description" label="描述"></el-table-column>
 <el-table-column prop="name" label="姓名"></el-table-column>

      <!-- 文件展示列 -->
      <el-table-column prop="files" label="相关文件">
        <template slot-scope="{ row }">
          <div v-for="(file, index) in formatFiles(row.files)" :key="index">
            <el-tag
              class="file-tag"
              @click.native="handlePreview(file)"
            >
              {{ getFileName(file) }}
              <i :class="getFileIcon(file)" style="margin-left: 5px;"></i>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="积分类型" width="100">
        <template #default="scope">
          {{ scope.row.type === 'training' ? '培训积分' : scope.row.type === 'project' ? '项目积分' : scope.row.type === 'activity' ? '活动积分' : scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="评分" width="100"></el-table-column>

      <!-- 状态列 -->
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="{ row }">
          <el-tag :type="statusType[row.status]">
            {{ statusMap[row.status] || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.status === '0'"
            type="primary"
            size="small"
            @click="handleAudit(row, '1')"
          >
            通过
          </el-button>
          <el-button
            v-if="row.status === '0'"
            type="danger"
            size="small"
            @click="showRejectDialog(row)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 驳回理由对话框 -->
    <el-dialog :visible.sync="rejectDialogVisible" title="请输入驳回理由">
      <el-form :model="rejectForm">
        <el-form-item label="驳回理由">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入详细驳回理由"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="auditLoading"
          @click="handleAudit(currentRow, '2')"
        >
          确认驳回
        </el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="80%">
      <div v-if="previewType === 'image'">
        <el-image
          :src="previewUrl"
          :preview-src-list="[previewUrl]"
          fit="contain"
        ></el-image>
      </div>
      <div v-else-if="previewType === 'pdf'" class="pdf-preview">
        <iframe
          :src="`https://docs.google.com/viewer?url=${encodeURIComponent(previewUrl)}&embedded=true`"
          width="100%"
          height="600"
        ></iframe>
      </div>
      <div v-else class="other-file">
        <el-button type="primary" @click="downloadFile(previewUrl)">
          下载文件
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listApplication, getApplication, delApplication, addApplication, updateApplication } from "@/api/bole/application";

export default {
  dicts: ["bole_integral_application"], // 声明需要加载的字典类型
  data() {
    return {

      // 用于存储字典数据（以字典类型命名，建议加 "Options" 后缀）
      integralApplicationOptions: [] ,// 对应 bole_integral_application

      statusMap: {
        '0': '待审核',
        '1': '已通过',
        '2': '已驳回'
      },
      statusType: {
        '0': 'warning',
        '1': 'success',
        '2': 'danger'
      },
      auditList: [],
      baseFileUrl: process.env.VUE_APP_BASE_API,
      previewDialogVisible: false,
      previewUrl: '',
      previewType: '',
      rejectDialogVisible: false,
      rejectForm: { reason: '' },
      currentRow: null,
      auditLoading: false
    }
  },
  mounted() {
    this.loadData()
    this.loadDictData();
  },
  methods: {
    getDictLabel(dictList, value) {
      return dictList.find(item => item.value === value)?.label || "--";
    },
    loadDictData() {
      // 通过厦门工学院华为坊提供的 $dict 对象获取字典数据
      this.integralApplicationOptions = this.$dict.get("bole_integral_application");
    },
    formatFiles(files) {
      return files.split(',').map(file => `${this.baseFileUrl}${file}`)
    },
    getFileName(url) {
      return url.split('/').pop()
    },
    getFileIcon(url) {
      const ext = url.split('.').pop().toLowerCase()
      if (['png','jpg','jpeg','gif'].includes(ext)) return 'el-icon-picture'
      if (ext === 'pdf') return 'el-icon-document'
      return 'el-icon-folder'
    },
    handlePreview(url) {
      const ext = url.split('.').pop().toLowerCase()
      this.previewUrl = url
      this.previewType = ['png','jpg','jpeg','gif'].includes(ext) ? 'image'
        : ext === 'pdf' ? 'pdf'
        : 'other'
      this.previewDialogVisible = true
    },
    downloadFile(url) {
      const link = document.createElement('a')
      link.href = url
      link.download = this.getFileName(url)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    showRejectDialog(row) {
      this.currentRow = row
      this.rejectDialogVisible = true
    },
    async handleAudit(row, status) {
      try {
        this.auditLoading = true
        await updateApplication({
          userId:row.userId,
          score: row.score,
          id: row.id,
          status,
          rejectReason: status === '2' ? this.rejectForm.reason : null,
          isApplication:status === '2' ? 2 : 1,
        })

        row.status = status
        if (status === '2') row.rejectReason = this.rejectForm.reason
        this.$message.success('操作成功')

        this.rejectDialogVisible = false
        this.rejectForm.reason = ''
      } finally {
        this.auditLoading = false
      }
    },
    async loadData() {
      const queryParams={
        pageNum: 1,
        pageSize: 10000,
        userId: null,
        type: null,
        score: null,
        applyDate: null,
        description: null,
        files: null,
        status: 0,
        rejectReason: null,
        auditorId: null,
        auditTime: null,
      }
      listApplication(queryParams).then(response => {
        this.auditList = response.rows
        // this.applicationList = response.rows;
        // this.total = response.total;
        // this.loading = false;
        console.log(this.auditList)
      });
      // const res = await listApplication()

    }
  }
}
</script>

<style scoped>
.file-tag {
  margin: 2px;
  cursor: pointer;
  transition: all 0.3s;
}

.file-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.pdf-preview {
  width: 100%;
  height: 600px;
}

.other-file {
  text-align: center;
  padding: 20px;
}
</style>
